<?
class ToeF_Layout {
	private $layoutname, $layoutdir, $callback;
	public $config;
	function __construct($layoutname) {
		global $tpLayoutDir, $layoutdir;

		$this->layoutname = $layoutname;
		$this->layoutdir = APP_ROOT."$tpLayoutDir/$layoutname";
	}

	function build($page) {
		global $config;

		if ( file_exists("$page->pageaddr.php") )
			include "$page->pageaddr.php";

		ob_start();
		print "<!-- main start -->\n";
		include "$page->pageaddr.phtml";
		print "<!-- end of main -->\n";
		$this->bodycontent = ob_get_contents();
		ob_end_clean();

		$this->send_http_header();
		$page->send_http_header();
		
		$document = '';
		$document .= $page->dtd($this->htmlversion);
		$document .= $page->html($this->htmlversion);
		$document .= $this->build_head_part($page);
		$document .= $this->build_body_part($page);
		$document .= "</html>";

		return $document;
	}

	function build_head_part($page) {
		$document .= "<head>\n";
		$document .= $this->build_header();
		$document .= $page->build_header();
		$document .= "</head>\n\n";
		return $document;
	}

	function build_body_part($page) {
		$document .= "<body>\n";
		$document .= $page->build_head();
		$document .= $this->build_head();

		/* no body file handled already on $page->build() */
		$document .= $this->bodycontent;
		
		$document .= $this->build_foot();
		$document .= $page->build_foot();
		$document .= "</body>\n";
		return $document;
	}
	
	function send_http_header() {
		global $tpHttpHeaderFile;
		if_exists_include("$this->layoutdir/$tpHttpHeaderFile");
	}

	function build_header() {
		global $tpHeaderFile;
		$result = '';
		if ( file_exists("$this->layoutdir/style.css") )
			$result .= import_css('../resource.php?type=layout&name='.$this->layoutname);
		if ( file_exists("$this->layoutdir/script.js") )
			$result .= import_js('../resource.php?type=layout&name='.$this->pagename);
		$result .= if_exists_get_contents("$this->layoutdir/$tpHeaderFile");
		return $result;
	}

	function build_head() {
		global $tpHeadFile;
		return if_exists_get_contents("$this->layoutdir/$tpHeadFile");
	}

	function build_foot() {
		global $tpFootFile;
		return if_exists_get_contents("$this->layoutdir/$tpFootFile");
	}
}
